<template>
  <div class="login">
    <!--  顶部导航返回 -->
    <van-nav-bar left-arrow @click-left="$router.push('/')" />
    <h1 class="title">短信登录</h1>
    <van-form   ref="form">
      <van-field v-model="form.mobile" name="mobile" placeholder="请输入手机号"
      :rules="[
        { required: true },
        {pattern:/^1[3-9]\d{9}/,message:'手机号格式错误'}
    ]"
      />
      <van-field v-model="form.code" name="password" type="password" placeholder="请输入验证码"
      :rules="[
        {required: true},
        {pattern:/\d{6}/,message:'验证码位6位'}
      ]"
    />
    </van-form>
    <button class="van-btn" @click="btnClick">{{ sendTime>0?`${sendTime}秒后即可发送` : '发送验证码' }}</button>
    <div>
      <van-button class="btn" block @click="login">登录</van-button>
    </div>
  </div>
</template>

<script>
import { verification } from '@/api/user'
export default {
  name: 'loginPage',
  data() {
    return {
      form: { // 输入框收集数据
        mobile: '17612345678',
        code: '246810'
      },
      sendTime: 0, // 倒计时
      timer: null // 节流

    }
  },
  methods: {
    // 发送验证码逻辑
    async btnClick() {
      if (this.sendTime > 0) return
      await this.$refs.form.validate('mobile') // 验证手机号
      const message = await verification(this.form.mobile) // 调用发送验证码接口
      if (message) {
        this.$toast.success('发送成功')
      }
      // 节流
      this.sendTime = 60
      this.timer = setInterval(() => {
        this.sendTime--
        if (this.sendTime <= 0) {
          clearInterval(this.timer)
        }
      }, 1000)
    },
    // 登录逻辑
    async login() {
      try {
        await this.$refs.form.validate()
        await this.$store.dispatch('user/login', this.form) // 调用actions 请求数据
        this.$router.push('/user')
        this.$store.commit('user/UPDATE_Active', 3)
      } catch {
      }
    }

  }

}
</script>

<style lang="less" scoped>
.login {
  /deep/ .van-icon {
    color: #333;
  }
  .title {
    margin-left: 64px;
    margin-top: 196px;
    font-size: 48px;
  }

  .van-field {
    width: 618px;
    padding: 0;
    padding-bottom: 39.5px;
    margin-top: 75.5px;
    background-color: #fff;
    font-size: 32px;
    margin-left: 64px;
    border-bottom: 1px solid #F0F0F0;
    position: relative;

  }
  .btn {
    margin-top: 76px;
    background:linear-gradient(to left,#FF9999 100% ,#FFA179 100% );
    width: 618px;
    height: 99.1px;
    margin: 76px  auto;
    border-radius: 8px;
  }
  .van-btn{
      position: absolute;
      top: 589px;
      left: 513px;
      font-size: 28px;
      color:#595769;
      border:0;
      background-color:#fff;
    }
}
</style>
